package org.framework.web.core.filter;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;

import static org.framework.web.core.constant.Constant.CONTENT_TYPE_HTML;
import static org.framework.web.core.constant.Constant.ENCODING_UTF8;

/**
 * 编码过滤器
 */
@Slf4j
public class CharacterEncodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) {
        log.info("CharacterEncodingFilter init() start.");
        encoding = filterConfig.getInitParameter(ENCODING_UTF8);
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
        log.info("CharacterEncodingFilter doFilter() start.");
        log.info("CharacterEncodingFilter doFilter() encoding: {}", ENCODING_UTF8);
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType(CONTENT_TYPE_HTML);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
